package sisi.products;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;
import sisi.categories.CategoriesController;
import sisi.categories.Category;


/**
 * ProductsWindow.java - Controller class for <i>Product's window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 12/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class ProductsWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxProducts
	private Window windowProducts, windowEditProduct;
	private Textbox tbCerca;
	private Listbox boxProducts;

	private List tutti_i_prodotti;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object productItem;
	private Product modProduct;
	// edit
	private Intbox id, idcategory;
	private Textbox productname, partnumber, desccategory, note;
	private Doublebox purcprice, saleprice;
	private Radio fuel, oil, bert, spare, other;

	public void onCreate$windowProducts(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_prodotti = new ProductsController().getProductList(null);
		listModelList.addAll(tutti_i_prodotti);
		boxProducts.setModel(listModelList);
		boxProducts.setItemRenderer(new ProductsItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_prodotti.size(); i++) {
				Product product = (Product)tutti_i_prodotti.get(i);
				if (product.getId()==idSelezionato.intValue()){
					boxProducts.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_prodotti = new ProductsController().getProductList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_prodotti);
		boxProducts.setModel(listModelList);
		boxProducts.setItemRenderer(new ProductsItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxProducts.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oProduct = boxProducts.getSelectedItem().getAttribute(
					"rigaProduct");
			String codiceSelezionato = ""+((Product) oProduct).getId();
			Sessions.getCurrent().setAttribute("codiceProductSelezionato",
					codiceSelezionato);
			windowProducts.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxProducts.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Product to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxProducts", boxProducts);
				Window finestraEditProduct = (Window) Executions.createComponents(
						"/editProduct.zul", null, map);
				finestraEditProduct.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class ProductsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Product) data).getId()).setParent(li);
			new Listcell(((Product) data).getProductname()).setParent(li);
			new Listcell(((Product) data).getPartno()).setParent(li);
			li.setAttribute("rigaProduct", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT PRODUCT: NEW/MODIFY
	public void onCreate$windowEditProduct(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxProducts = (Listbox) args.get("boxProducts");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			productItem = boxProducts.getSelectedItem().getAttribute("rigaProduct");
			modProduct = new ProductsController().refreshProduct((Product) productItem);
			productItem = modProduct;
			windowEditProduct.setTitle("Edit Product");
			productname.setFocus(true);
			id.setValue(modProduct.getId());
			productname.setValue(modProduct.getProductname());
			partnumber.setValue(modProduct.getPartno());
			purcprice.setValue(modProduct.getPurcprice());
			saleprice.setValue(modProduct.getSaleprice());
			idcategory.setValue( (modProduct.getCategoryid()!=null?modProduct.getCategoryid():0));
			Category categ = new CategoriesController().getCategoryxId(modProduct.getCategoryid());
			desccategory.setValue( (categ.getCategoryname()!=null&&!categ.getCategoryname().isEmpty())?categ.getCategoryname():"");
			note.setValue(modProduct.getNote());
			fuel.setChecked(modProduct.getFuel());
			oil.setChecked(modProduct.getOil());
			bert.setChecked(modProduct.getBert());
			spare.setChecked(modProduct.getSpare());
			other.setChecked(modProduct.getOth());
		} else {
			windowEditProduct.setTitle("New Product");
			productname.setFocus(true);
		}

	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditProduct.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modProduct = new Product();
		} else {

		}
		String testoMsg = "";

		modProduct.setBert(bert.isChecked());
		modProduct.setCategoryid(idcategory.getValue());
		modProduct.setFuel(fuel.isChecked());
		modProduct.setId(id.getValue());
		modProduct.setNote(note.getValue());
		modProduct.setOil(oil.isChecked());
		modProduct.setOth(other.isChecked());
		modProduct.setPartno(partnumber.getValue());
		modProduct.setProductname(General.toUpperAncheNull(productname.getValue()));
		modProduct.setPurcprice( ( purcprice.getValue()!=null?purcprice.getValue():0) );
		modProduct.setSaleprice( (saleprice.getValue()!=null?saleprice.getValue():0) );
		modProduct.setSpare(spare.isChecked());
	
		if (lNuovo){
			new ProductsController().addProduct(modProduct);
			testoMsg = "Adding Product: "+ General.trimNull( modProduct.getProductname() );
		} else {
			new ProductsController().updateProduct(modProduct);
			testoMsg = "Updating Product: "+ General.trimNull( modProduct.getProductname() );			
		}
		
		General.showNotify( testoMsg, windowEditProduct);		
		
		windowEditProduct.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxProducts.getListModel();
			lml.add(modProduct);
			boxProducts.setSelectedIndex(lml.indexOf(modProduct));
		} else {
			ListModelList lml = (ListModelList) boxProducts.getListModel();
			Object oProductItem = boxProducts.getSelectedItem().getAttribute("rigaProduct");
			if (lml.indexOf(oProductItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oProductItem), modProduct);
			}
		}		
	}
	
	public void onClick$btnCategory(Event event){
		Sessions.getCurrent().setAttribute("codiceCategorySelezionato",
			"");
		HashMap map = new HashMap();
		map.put("tastoSeleziona", "S");
		map.put("idselezionato", idcategory.getValue());
		Window winCorp = (Window) Executions.createComponents(
				"/categories.zul", null, map);
		winCorp.doModal();
		String codiceSelezionato = (String) Sessions.getCurrent()
				.getAttribute("codiceCategorySelezionato");
		if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
			Category corp = new CategoriesController().getCategoryxId(Integer.valueOf(codiceSelezionato));
			desccategory.setValue(corp.getCategoryname());
			idcategory.setValue(corp.getCategoryid());
		}
	}
	
}
